package p2p;

import java.util.Scanner;
import java.io.File;
import java.util.InputMismatchException;
import java.io.FileNotFoundException;
import java.security.NoSuchAlgorithmException;
import java.io.IOException;

/** Command Line Interface for the project
 * @author ei08150
 */

public class CLIFrontend {
    private static Scanner input = new Scanner(System.in);

	public static void start() {
		banner();

		initialMenu();
	}

	public static void banner() {
		System.out.println(" ____ ____  ____            _ _     ");
		System.out.println("|  _ \\___ \\|  _ \\   ___  __| (_)___ ");
		System.out.println("| |_) |__) | |_) | / __|/ _` | / __|");
		System.out.println("|  __// __/|  __/  \\__ \\ (_| | \\__ \\");
		System.out.println("|_|  |_____|_|     |___/\\__,_|_|___/");
	}

	public static void initialMenu() {

        int userInput = 0;

        while (true) {
            System.out.println("1. Add a file to be shared");
            System.out.println("2. Search for a file on the network");
            System.out.println("3. Quit");
            System.out.print("Option [1-3]: ");

            try {
                userInput = input.nextInt();
            }
            catch (InputMismatchException e) {
                // Limpar o conteudo do Scanner
                input.nextLine();
            }

            switch (userInput) {
            case 1:
                addFileMenu();
                break;
            case 2:
                searchFileMenu();
                break;
            case 3:
                // Necessario usar System.exit porque senao as outras
                // threads, como controlPortThread, ainda continuavam
                // a ser executadas
                System.exit(0);
            default:
                System.out.println("Invalid option.");
                System.out.println();
            }
        }
    }

    public static void addFileMenu() {
        // TODO: Permitir adicionar varios ficheiros de uma so vez?

        System.out.println("What file do you wish to share? (type \"quit\" to exit)");
        System.out.print("> ");
        // TODO: permitir adicionar os ficheiros todos de uma pasta
        String filename = new String();

        // Este Scanner.nextLine() simplesmente faz o flush do buffer do Scanner
        input.nextLine();


        filename += input.nextLine();

        if (filename.toLowerCase().equals("quit")) {
            return;
        }
        
        File fileToShare = new File(filename);

        // Can't share a non-existent file
        if (!fileToShare.exists()) {
            System.out.println("File couldn't be found.");
            return;
        }

        P2PFile p2pFileToShare = null;
        
        try {
            p2pFileToShare = new P2PFile(fileToShare);
        }
        catch (FileNotFoundException e) {
            // This should happen because the existance of the file
            // has already been checked
            e.printStackTrace();
        }
        catch (NoSuchAlgorithmException e) {
            // Don't know what to do here
            e.printStackTrace();
            return;
        }
        catch (IOException e) {
            // Don't know what to do here
            e.printStackTrace();
            return;
        }

        boolean fileAddedSuccessfully = P2PFileList.addFile(p2pFileToShare);

        if (!fileAddedSuccessfully) {
            System.out.println("File was already been shared.");
        }
    }

    public static void searchFileMenu() {
        System.out.println("What keywords do you wish to search? (type \"quit\" to exit)");
        System.out.print("> ");
        // TODO: permitir adicionar os ficheiros todos de uma pasta
        String keywords = new String();

        // Este Scanner.nextLine() simplesmente faz o flush do buffer do Scanner
        input.nextLine();

        keywords += input.nextLine();

        if (keywords.toLowerCase().equals("quit")) {
            return;
        }

        SearchList.startSearch(keywords);

        // Esperar
    }
}
